package com.zzl.myblog.View.Fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zzl.myblog.Bean.ResponseBean.NavigationDataBean;
import com.zzl.myblog.Bean.ResponseBean.SystemBean;
import com.zzl.myblog.Bean.ViewBean.TagsSimpleBean;
import com.zzl.myblog.R;
import com.zzl.myblog.Utils.HttpUtil;
import com.zzl.myblog.Utils.LogUtil;
import com.zzl.myblog.Utils.responseUtility;
import com.zzl.myblog.View.Adapter.TagsAdapter;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 导向界面
 *  - 知识体系
 *  - 拓维导航 复用同一个模板碎片：LeadFragment
 * 使用位置：FragmentFactoryUtil.java
 *
 */
public class LeadFragment extends Fragment {
    String username;
    String TAG = "LeadFragment";
    String strKind; // 是“知识体系“还是“拓维导航”
    View rootView;

    private Unbinder unbinder;

    @BindView(R.id.srl_sf)
    RefreshLayout refreshLayout;


    @BindView(R.id.rv_fragment_system)
    RecyclerView mRecyclerView;

    @BindView(R.id.go_top)
    FloatingActionButton floatingActionButton;

    TagsAdapter tagsAdapter;

    //知识体系-数据源
    private List<SystemBean.DataBean> systemDataBeanList;
    private List<TagsSimpleBean> systemSimpleBeanList = new ArrayList<>();

    //拓维导航-数据源
    private List<NavigationDataBean.DataBean> naviDataBeanList;
    //简化Bean类与知识体系的相同，复用此类实例systemSimpleBeanList

    //无参构造
    public LeadFragment() {
        // Required empty public constructor
    }

    //分类，知识体系和拓维导航两种碎片leadFragment中包含两个碎片
    public static LeadFragment newInstance(String arg ,String username) {
        LeadFragment fragment = new LeadFragment();

        Bundle bundle = new Bundle();
        bundle.putString("kind", arg);
        bundle.putString("username", username);

        fragment.setArguments(bundle); // 绑定 bundle

        return fragment;
    }

    // 拿到 strKind 、 username
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_system, container, false);

        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, rootView);

        //拿到kind类型值
        strKind = getArguments().getString("kind");
        username = getArguments().getString("username");

        // 初始化RecycleView 和 RefreshLayout
        initView();

        // initData
        initData();

        return rootView;
    }

    // 初始化RecyclerView RefreshLayout
    private void initView() {
        //top rv
        mRecyclerView.setHasFixedSize(true);

        //平常的水平一个item布局的流
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        //利用refreshLayout手动刷新UI界面
        refreshLayout.autoRefreshAnimationOnly();
        refreshLayout.finishRefresh(1100/*,false*/);//传入false表示刷新失败//手动设置动画时长为一秒
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                // 数据集置空，重新加载
                systemSimpleBeanList.clear();
                switch (strKind) { // 检测当前再那个fragment
                    case "tree":
                        // 跳到 初始化知识体系
                        initTree();
                        break;
                    case "navigation":
                        // 跳到 初始化拓维导航
                        initNavigation();
                        break;
                }
                tagsAdapter.notifyDataSetChanged(); // 更新rv
                refreshLayout.finishRefresh(2000/*,false*/);    // 结束刷新
                Toast.makeText(getActivity(),"刷新成功！",Toast.LENGTH_SHORT).show();
            }
        });

        // 跳转到界面顶部
        floatingActionButton.setOnClickListener(v -> {
            layoutManager.scrollToPosition(0);
        });
    }

    // initData
    private void initData() {
        switch (strKind) {  // 检测当前是那个fragment，请求对应的数据
            case "tree":
                // 跳到 初始化知识体系
                initTree();
                break;
            case "navigation":
                // 跳到 初始化拓维导航
                initNavigation();
                break;
        }
        /*
            只有上述代码执行完后，下部代码才有效
         */
        //实例化 MyAdapter 并传入mList对象
        tagsAdapter = new TagsAdapter(systemSimpleBeanList,username);
        //rv 绑定
        mRecyclerView.setAdapter(tagsAdapter);
        Toast.makeText(getActivity(),"加载成功！",Toast.LENGTH_SHORT).show();
    }

    // 请求API，获取到知识体系数据源
    private void initTree() {
        HttpUtil.wanAndroid_GET("tree/json", "",new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String JSON = response.body().string();
                    SystemBean systemBean = responseUtility.parse_initTree(JSON);
                    systemDataBeanList = systemBean.getData();
                    for(SystemBean.DataBean item : systemDataBeanList){
                        // ChildrenBeanList
                        List<SystemBean.DataBean.ChildrenBean> childrenBeanList = item.getChildren();

                        String[] mVals = new String[childrenBeanList.size()]; // name List
                        String[] webURLs = new String[childrenBeanList.size()];//webURL List

                        for (int index = 0; index < childrenBeanList.size(); index++) {
                            mVals[index] = childrenBeanList.get(index).getName();
                            webURLs[index]="https://www.wanandroid.com/article/list/0?cid="
                                    +childrenBeanList.get(index).getId();
                            //Log.d(TAG, "child: " + childrenBeanList.get(index).getName());
                        }
                        // 封装 TagsSimpleBean
                        TagsSimpleBean systemSimpleBean = new TagsSimpleBean(item.getName(), mVals,webURLs);
                        // 将封装好的一个TagsSimpleBean 加到数据源systemSimpleBeanList
                        systemSimpleBeanList.add(systemSimpleBean);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtil.i(TAG,"初始化知识体系-请求失败");
            }
        });
    }

    // 请求API，获取拓维导航数据源
    private void initNavigation() {
        HttpUtil.wanAndroid_GET("navi/json","", new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String json = response.body().string();
                    NavigationDataBean navigationDataBean = responseUtility.parse_initNavigation(json);
                    naviDataBeanList = navigationDataBean.getData();
                    for(NavigationDataBean.DataBean item : naviDataBeanList){
                        List<NavigationDataBean.DataBean.ArticlesBean> articlesBeanList = item.getArticles();

                        String[] mVals = new String[articlesBeanList.size()];
                        String[] webURLs = new String[articlesBeanList.size()];

                        for (int index = 0; index < articlesBeanList.size(); index++) {
                            //初始化mVals 标签String数组
                            mVals[index] = articlesBeanList.get(index).getTitle();

                            ////初始化webURLs 标签对应的web链接,统一成https
                            String url = articlesBeanList.get(index).getLink();
                            if (!url.contains("https")) {
                                //http://www.wanandroid.com/blog/show/2658 //第五个位置添加s
                                StringBuffer strhttps = new StringBuffer();
                                strhttps.append(url).insert(4, "s");
                                url= strhttps + "";

                            }
                            webURLs[index] = url;
                            // Log.d(TAG, "child: " + articlesBeanList.get(index).getLink());
                        }
                        TagsSimpleBean systemSimpleBean = new TagsSimpleBean(item.getName(), mVals, webURLs);
                        systemSimpleBeanList.add(systemSimpleBean);
                    }
                }catch(Exception e){
                   e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(getActivity(), "初始化拓维导航失败", Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}
